﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection.Metadata;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using Quartz.Impl;
using Quartz;
using Quartz.Logging;
using Quartz.Impl.Matchers; 
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace CarparkBusiness
{
    public partial class CarParkingScheduleTask
    { 
        public static string[] Args { get; set; }
         
        public static async Task RunTask(string[] args,int intervalMinutes)
        {
            Args = args;
#if DEBUG
            intervalMinutes = 1;
#endif
            DateTime TaskStartDate = DateTime.Now;

            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };

                StdSchedulerFactory factory = new StdSchedulerFactory(props);

                IScheduler scheduler = await factory.GetScheduler();

                await scheduler.Start();

                IJobDetail job = JobBuilder.Create<ScheduleJob>()
                    .WithIdentity("JobUnitClac1", "GroupUnitClac1")
                    .Build();
                 
                ITrigger trigger = TriggerBuilder.Create()
                   .WithIdentity("triggerUnitClac1_GroupUnitClac1")
                   .StartAt(TaskStartDate)
                   .ForJob("JobUnitClac1", "GroupUnitClac1")
                   .WithCalendarIntervalSchedule(w => w.WithInterval(intervalMinutes, IntervalUnit.Minute))
                   .Build();

                await scheduler.ScheduleJob(job, trigger); 
            }
            catch (SchedulerException se)
            {
                await Console.Error.WriteLineAsync(se.ToString());
            }
        }

        public class ScheduleJob : IJob
        {
            public async Task Execute(IJobExecutionContext context)
            {
                BackgroundServiceStatus backgroundService =  BackgroundServiceStatus.Get();
                bool IsStopped = false;
 #if DEBUG 
                IsStopped = backgroundService.IsStopped ;
                var services = new ServiceCollection();
                TaskStartUp.ConfigureServices(services);
                var serviceProvider = services.BuildServiceProvider();
                await serviceProvider.GetService<MainCalcControlLer>().Run(Args);
                string loggerLineJob =$"\n[{DateTime.Now:yyyy-MM-dd HH:mm:ss fff}] [INFO] [Execute::MainCalcControlLer.Run:{context.FireInstanceId}] [BACKGROUND IN SERVICE!!!][IsStopped={IsStopped}]";
                await Console.Out.WriteLineAsync(loggerLineJob);
                return;
#endif

#if RELEASE
                if (!IsStopped)
                {
                    var services = new ServiceCollection(); 
                    TaskStartUp.ConfigureServices(services);
                    var serviceProvider = services.BuildServiceProvider();
                    await serviceProvider.GetService<MainCalcControlLer>().Run(Args);
                    string loggerLineJob =$"\n[{DateTime.Now:yyyy-MM-dd HH:mm:ss fff}] [INFO] [Execute::MainCalcControlLer.Run:{context.FireInstanceId}] [BACKGROUND IN SERVICE!!!][IsStopped={IsStopped}]";
                    await Console.Out.WriteLineAsync(loggerLineJob);
                    return;
                }
                else
                {
                    string loggerLineServiceStopJob = string.Format("\n[{0:yyyy-MM-dd HH:mm:ss fff}] [BACKGROUND SERVICE STOPPED!!!] [Execute::MainCalcControlLer.Run:{1}][IsStopped={2}]", DateTime.Now, context.FireInstanceId,IsStopped);
                    Common.CommonBase.OperateDateLoger(loggerLineServiceStopJob);
                    await Console.Out.WriteLineAsync(loggerLineServiceStopJob);
                }
#endif
            }
        }
    }
}
